package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private RabbitService rabbitService;


    //获取一级分类数据
    @Override
    public List<BaseCategory1> getCategory1() {
        //select * from base_category1;
        return baseCategory1Mapper.selectList(null);
    }

    //根据一级分类Id，获取二级分类数据
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //select * from base_category2 where category1_id = category1Id;
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id",category1Id));
    }

    //根据二级分类Id，获取三级分类数据
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //select * from base_category3 where category2_id = category2Id;
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id",category2Id));
    }

    //根据分类Id，获取平台属性
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        // 需要调用mapper
        // 查询平台属性的时候，可以顺便把平台属性值查出来
        // 多表关联查询，必须使用mapper.xml
        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id);
    }

    //保存平台属性
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //id为空是保存，不为空是修改
        if (baseAttrInfo.getId() == null) {
            //base_attr_info
            baseAttrInfoMapper.insert(baseAttrInfo);
        } else {
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }

        //修改（先删除再新增）
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete(queryWrapper);

        //base_attr_value
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)) {
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }
    }

    //根据attr_id获取平台属性值
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //select * from base_attr_value where attr_id = ?
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id",attrId));
    }

    //根据属性id获取属性数据
    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //获取平台属性对象
        BaseAttrInfo baseAttrInfo = this.baseAttrInfoMapper.selectById(attrId);
        if (baseAttrInfo != null) {
            //赋值平台属性值集合数据
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        return baseAttrInfo;
    }

    //根据分类id 查询SpuInfo 的集合数据
    @Override
    public IPage getSpuList(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {
        //  select * from spu_info where category3_id = 61 limit 0, 10;
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        //  加点细节： 按照id 进行排序 desc
        spuInfoQueryWrapper.orderByDesc("id");
        return spuInfoMapper.selectPage(spuInfoPage,spuInfoQueryWrapper);
    }

    //获取销售属性列表
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //保存spu
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        // spu_info
        spuInfoMapper.insert(spuInfo);
        // spu_image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.stream().forEach(spuImage -> {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        // spu_poster
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            spuPosterList.stream().forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }
        // spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.stream().forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                // spu_sale_attr_value
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
    }

    //获取spuInfo 相关信息
    @Override
    public SpuInfo getSpuInfo(Long spuId) {
        // 查询到spuInfo 数据集
        SpuInfo spuInfo = this.spuInfoMapper.selectById(spuId);

        // 根据spuId 来获取销售属性数据
        QueryWrapper<SpuSaleAttr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.selectList(queryWrapper);

        // 根据spu_id 与 base_sale_attr_id 找到销售属性对应的属性值！
        spuSaleAttrList.forEach(spuSaleAttr -> {
            QueryWrapper<SpuSaleAttrValue> valueQueryWrapper = new QueryWrapper<>();
            valueQueryWrapper.eq("spu_id",spuId);
            valueQueryWrapper.eq("base_sale_attr_id",spuSaleAttr.getBaseSaleAttrId());
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttrValueMapper.selectList(valueQueryWrapper);

            spuSaleAttr.setSpuSaleAttrValueList(spuSaleAttrValueList);
        });
        spuInfo.setSpuSaleAttrList(spuSaleAttrList);

        // 获取图片信息
        List<SpuImage> spuImageList = spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
        spuInfo.setSpuImageList(spuImageList);

        // 获取海报信息
        List<SpuPoster> spuPosterList = spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id", spuId));
        spuInfo.setSpuPosterList(spuPosterList);

        // 返回
        return spuInfo;
    }

    //更新spuInfo 相关信息
    @Override
    public void updateSpuInfo(SpuInfo spuInfo) {
        spuInfoMapper.updateById(spuInfo);

        //删除图片
        spuImageMapper.delete(new QueryWrapper<SpuImage>().eq("spu_id",spuInfo.getId()));
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.stream().forEach(spuImage -> {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }

        //删除海报
        spuPosterMapper.delete(new QueryWrapper<SpuPoster>().eq("spu_id",spuInfo.getId()));
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            spuPosterList.stream().forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }

        //删除销售属性
        spuSaleAttrMapper.delete(new QueryWrapper<SpuSaleAttr>().eq("spu_id",spuInfo.getId()));
        spuSaleAttrValueMapper.delete(new QueryWrapper<SpuSaleAttrValue>().eq("spu_id",spuInfo.getId()));
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.stream().forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                //销售属性值集合
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
    }

    //根据spuId 获取spuImage 集合
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id",spuId));
    }

    //根据spuId 查询销售属性
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    //保存skuInfo
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //sku_info
        skuInfoMapper.insert(skuInfo);
        //sku_image
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //sku_attr_value
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        //sku_sale_attr_value
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
    }

    //查询skuInfo分页列表
    @Override
    public IPage getSkuInfoList(Page<SkuInfo> skuInfoPage, SkuInfo skuInfo) {
        //select * from sku_info where category3_id = ? and is_deleted = 0 order by id desc limit 0,10
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id",skuInfo.getCategory3Id());
        queryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage,queryWrapper);
    }

    //上架商品
    @Override
    public void onSale(Long skuId) {
        // 本质 修改 is_sale = 1
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);

        // 发送消息：看上架需要什么 skuId
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    //下架商品
    @Override
    public void cancelSale(Long skuId) {
        // 本质 修改 is_sale = 0
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);

        // 发送消息：看上架需要什么 skuId
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Override
    @GmallCache(prefix = "sku:")
    public SkuInfo getSkuInfo(Long skuId) {
        //return getSkuInfoByRedisson(skuId);

        return getSkuInfoDB(skuId);
    }

    private SkuInfo getSkuInfoByRedisson(Long skuId) {
        //return getSkuInfoByRedis(skuId);
        // skuKey = sku : skuId : info
        String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        try {
            // 获取数据
            SkuInfo skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            // 判断缓存中有没有数据
            if (skuInfo==null) {
                // 缓存中没有数据，查询数据库之前，添加一把锁
                // 定义分布式锁的key
                String skuLockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
                RLock lock = this.redissonClient.getLock(skuLockKey);
                // 上锁
                // lock.lock();
                // lock.lock(10,TimeUnit.SECONDS);
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (result) {
                    // 获取到锁
                    try {
                        // 查询数据库，并放入缓存
                        skuInfo = this.getSkuInfoDB(skuId);
                        // 判断数据库中是否存在
                        if (skuInfo == null) {
                            SkuInfo skuInfo1 = new SkuInfo();
                            this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        // 数据中存在
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo;
                    }finally {
                        // 解锁
                        lock.unlock();
                    }
                }else {
                    try {
                        // 没获取到锁   自旋
                        Thread.sleep(1000);
                        return getSkuInfo(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }else {
                // 缓存中有数据
                return skuInfo;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 数据库兜底
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getSkuInfoByRedis(Long skuId) {
        // skuKey = sku : skuId : info
        String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        try {
            //获取数据
            SkuInfo skuInfo  = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            // 判断
            if (skuInfo == null) {
                // 缓存中没有数据，查询数据库之前，添加一把锁
                // 第一种方案：redis + lua
                // 定义分布式锁的key
                String skuLockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
                // 定义分布式锁的token
                String token = UUID.randomUUID().toString();
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(skuLockKey, token, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                // 判断是否获取到锁
                if (result) {
                    try {
                        // 获取到锁，查询数据库
                        skuInfo = this.getSkuInfoDB(skuId);
                        // 看数据库中有没有
                        if (skuInfo == null) {
                            // 将一个空对象放入缓存   （防穿透）
                            SkuInfo skuInfo1 = new SkuInfo();
                            this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        // 数据库中有数据，查询并放入缓存
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                        // 返回数据
                        return skuInfo;
                    } finally {
                        // 释放锁
                        // 定义lua脚本
                        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                        // 执行lua脚本
                        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                        // 将lua脚本放入DefaultRedisScript 对象中
                        redisScript.setScriptText(script);
                        // 设置DefaultRedisScript 这个对象的泛型
                        redisScript.setResultType(Long.class);
                        // 执行删除
                        redisTemplate.execute(redisScript, Arrays.asList("skuLockKey"),token);
                    }
                } else { // 没有获取到锁
                    // 睡眠，自旋
                    try {
                        Thread.sleep(1000);
                        return getSkuInfo(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                // 从缓存中获取数据
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getSkuInfoDB(skuId);
    }

    //根据skuId获取skuInfo + skuImageList
    private SkuInfo getSkuInfoDB(Long skuId) {
        // 获取skuInfo
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo!=null) {
            // 获取skuImageList
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            // 赋值
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }

    //获取最新商品价格数据
    @Override
    public BigDecimal getSkuPrice(Long skuId) {

        RLock lock = this.redissonClient.getLock(skuId + ":lock");
        lock.lock();
        try {
            // select price from sku_info where id = ?
            QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("price");
            queryWrapper.eq("id",skuId);
            SkuInfo skuInfo = skuInfoMapper.selectOne(queryWrapper);
            // 返回数据
            return skuInfo!=null?skuInfo.getPrice():new BigDecimal("0");
        } finally {
            lock.unlock();
        }
    }

    @Override
    public SkuInfo getFullSkuInfo(Long skuId) {
        //  获取skuInfo 数据
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //  获取图片集合数据
        QueryWrapper<SkuImage> skuImageQueryWrapper = new QueryWrapper<>();
        skuImageQueryWrapper.eq("sku_id",skuId);
        List<SkuImage> skuImageList = skuImageMapper.selectList(skuImageQueryWrapper);
        skuInfo.setSkuImageList(skuImageList);
        //  获取skuAttrValue | 因为 skuId 对应的平台属性名与平台属性值的名！
        List<SkuAttrValue> skuAttrValueList = skuAttrValueMapper.selectSkuAttrValue(skuId);
        skuInfo.setSkuAttrValueList(skuAttrValueList);
        //  获取skuSaleAttrValue
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuSaleAttrValueMapper.selectSkuSaleAttrValue(skuId);
        skuInfo.setSkuSaleAttrValueList(skuSaleAttrValueList);
        return skuInfo;
    }

    @Override
    public void updateSkuInfo(SkuInfo skuInfo) {
        //  更新数据
        skuInfoMapper.updateById(skuInfo);

        skuImageMapper.delete(new QueryWrapper<SkuImage>().eq("sku_id", skuInfo.getId()));
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (skuImageList != null && skuImageList.size() > 0) {

            // 循环遍历
            for (SkuImage skuImage : skuImageList) {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }

        skuSaleAttrValueMapper.delete(new QueryWrapper<SkuSaleAttrValue>().eq("sku_id", skuInfo.getId()));
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        // 调用判断集合方法
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }

        skuAttrValueMapper.delete(new QueryWrapper<SkuAttrValue>().eq("sku_id", skuInfo.getId()));
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            for (SkuAttrValue skuAttrValue : skuAttrValueList) {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }
    }


    // 通过三级分类id查询分类信息
    @Override
    @GmallCache(prefix = "categoryView:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        // select * from v_category where id = 61;
        return baseCategoryViewMapper.selectById(category3Id);
    }

    // 查询出sku对应spu的销售属性
    @Override
    @GmallCache(prefix = "spuSaleAttrList:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    // 根据spuId获取相关数据
    @Override
    @GmallCache(prefix = "skuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        HashMap<Object, Object> map = new HashMap<>();
        List<Map> mapList = skuSaleAttrValueMapper.selectSaleAttrValuesBySpuId(spuId);
        if (!CollectionUtils.isEmpty(mapList)) {
            for (Map maps : mapList) {
                map.put(maps.get("value_ids"),maps.get("sku_id"));
            }
        }
        return map;
    }

    // 获取海报信息
    @Override
    @GmallCache(prefix = "spuPoster:")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        return spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id",spuId));
    }

    // 获取平台属性数据
    @Override
    @GmallCache(prefix = "attrList:")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }

    // 获取首页分类数据
    @Override
    @GmallCache(prefix = "index:")
    public List<JSONObject> getBaseCategoryList() {
        // 声明集合
        List<JSONObject> list = new ArrayList<>();
        // 调用mapper查询所有数据
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        // 先声明一个变量
        int index = 1;
        // 获取一级分类数据  key : categoryId1   value  :  categoryViewList1
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        // 获取迭代器
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = category1Map.entrySet().iterator();
        while (iterator1.hasNext()) {
            Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
            // 获取key
            Long categoryId1 = entry1.getKey();
            // 获取value
            List<BaseCategoryView> categoryViewList1 = entry1.getValue();
            // 创建 JSONObject 对象   一级分类对象
            JSONObject category1 = new JSONObject();
            category1.put("index",index);
            category1.put("categoryId",categoryId1);
            category1.put("categoryName",categoryViewList1.get(0).getCategory1Name());

            index++;
            // 创建二级分类集合对象
            List<JSONObject> categoryChild2 = new ArrayList<>();
            // 获取二级分类数据   key : categoryId2   value  :  categoryViewList2
            Map<Long, List<BaseCategoryView>> category2Map = categoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            // 获取迭代器
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator2 = category2Map.entrySet().iterator();
            while (iterator2.hasNext()) {
                Map.Entry<Long, List<BaseCategoryView>> entry2 = iterator2.next();
                // 获取key
                Long categoryId2 = entry2.getKey();
                // 获取value
                List<BaseCategoryView> categoryViewList2 = entry2.getValue();
                // 创建 JSONObject 对象   二级分类对象
                JSONObject category2 = new JSONObject();
                category2.put("categoryId",categoryId2);
                category2.put("categoryName",categoryViewList2.get(0).getCategory2Name());

                // 将二级分类数据添加到二级分类集合
                categoryChild2.add(category2);

                // 创建三级分类集合对象
                List<JSONObject> categoryChild3 = new ArrayList<>();
                // 获取三级分类数据  key : categoryId3   value  :  categoryViewList3
                categoryViewList2.forEach(baseCategoryView -> {
                    // 创建 JSONObject 对象   三级分类对象
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    // 将三级分类数据添加到三级分类集合
                    categoryChild3.add(category3);
                });

                // 将三级分类数据添加到二级分类数据中
                category2.put("categoryChild",categoryChild3);
            }

            // 将二级分类数据添加到一级分类数据中
            category1.put("categoryChild",categoryChild2);

            // 将一级分类数据添加到list集合中
            list.add(category1);
        }
        return list;
    }

    // 通过品牌Id 集合来查询数据
    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }
}
